import { Typography, Input, Button, Tag, Space, message } from "antd";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import React, { useState, useEffect, useMemo } from "react";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig } from "@wangeditor/editor";
import axios from "axios";
import style from "./style.module.css";
import { PlusOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { useAppSelector } from "../../app/hooks";
export const PublishJob = () => {
  const navigate = useNavigate();
  // 富文本
  const [editor, setEditor] = useState<IDomEditor | null>(null); // 存储 editor 实例
  const [html, setHtml] = useState("<p>请描述职位信息</p>"); // 编辑器内容
  const toolbarConfig = {};
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: "请输入内容...",
  };
  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);
  // 标题
  const [title, setTitle] = useState("");
  // tab
  const [tabData, setTabData] = useState<
    {
      title: string;
      children: string[];
    }[]
  >([]);
  const [tabIndex, setTabIndex] = useState(0);
  const [show, setShow] = useState(false);
  const [isSearch, setIsSearch] = useState(false);
  const [search, setSearch] = useState("");
  const [typeList, setTypeList] = useState<{ type: string }[]>([]);
  // 获取仓库数据
  const nickname = useAppSelector(state=> state.user.nickname)
  const avator = useAppSelector(state=> state.user.avator)
  const handleChangeTabIndex = (i: number) => {
    setTabIndex(i);
  };
  const handleSelect = (v: string) => {
    setShow(false);
		setIsSearch(false)
    setTypeList([...typeList, { type: v }]);
  };
  const handleDelete = (i: number) => {
    setTypeList(typeList.filter((v, index) => index !== i));
  };
  const filterList = useMemo(() => {
    const list: { type: string }[] = [];
    tabData.forEach((v) => {
      v.children.forEach((v) => {
        if (v.includes(search)) {
          list.push({ type: v });
        }
      });
    });
		return list
  }, [search]);
  // 发布函数
  const handlePublish = () => {
    if (title.length === 0) {
      message.error("标题不可以为空");
      return;
    }
    if (typeList.length < 2) {
      message.error("标签最少选择2个");
      return;
    }
    if (html.length === 0) {
      message.error("内容不可以为空");
      return;
    }

    axios
      .post("/api/list/add", { typeList, title, content: html, avator, nickname })
      .then((resp) => {
        const { code, message: tip } = resp.data;
        message.success(tip);
        setTimeout(() => {
          navigate("/");
        }, 2000);
      });
  };

  useEffect(() => {
    const fetchTabData = async () => {
      const resp = await axios.get("/api/tab");
      setTabData(resp.data.data);
    };

    fetchTabData();
  }, []);

  return (
    <div>
      <Typography.Title level={1}>发布岗位</Typography.Title>
      <Input
        type="text"
        placeholder="请输入标题"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
      />
      <div style={{ margin: "10px 0" }} className={style["tab"]}>
        <Space>
          {typeList.map((v, i) => {
            return (
              <Tag closable key={i} onClick={() => handleDelete(i)}>
                {v.type}
              </Tag>
            );
          })}
          {typeList.length < 5 && (
            <Button onClick={() => setShow(true)} icon={<PlusOutlined />}>
              添加标签
            </Button>
          )}
        </Space>

        <div
          className={style["tab-dialog"]}
          style={{ display: show ? "block" : "none" }}
        >
          <Input.Search
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onSearch={() => {
              setIsSearch(true);
            }}
          ></Input.Search>
          {!isSearch ? (
            <div>
              <div className={style["title"]}>
                {tabData.map((v, i) => {
                  return (
                    <b
                      key={i}
                      onClick={() => handleChangeTabIndex(i)}
                      className={i === tabIndex ? style["active"] : ""}
                    >
                      {v.title}
                    </b>
                  );
                })}
              </div>
              <div className="content">
                {tabData.length > 0 &&
                  tabData[tabIndex].children.map((v, i) => {
                    return (
                      <Tag
                        key={i}
                        className={style["tag"]}
                        onClick={() => handleSelect(v)}
                      >
                        {v}
                      </Tag>
                    );
                  })}
              </div>
            </div>
          ) : (
            <ul>
              {filterList.map((v, i) => {
                return <li key={i} onClick={ () =>handleSelect(v.type) }>{v.type}</li>;
              })}
            </ul>
          )}
        </div>
      </div>
      {/* 富文本 */}
      <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: "1px solid #ccc" }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={(editor) => setHtml(editor.getHtml())}
          mode="default"
          style={{ height: "500px", overflowY: "hidden" }}
        />
      </div>
      <Button onClick={() => handlePublish()}>发布岗位</Button>
    </div>
  );
};
